package controllers

import (
	"NewEdu/models"
	"NewEdu/utils"
	"encoding/json"
	"strconv"
	"time"

	beego "github.com/beego/beego/v2/server/web"
)

// TExamAnswerController 考试答卷控制器
type TExamAnswerController struct {
	beego.Controller
}

// URLMapping ...
func (c *TExamAnswerController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
	c.Mapping("GetByExamId", c.GetByExamId)
	c.Mapping("GetByStudentSn", c.GetByStudentSn)
	c.Mapping("GetByStudentSnAndExamId", c.GetByStudentSnAndExamId)
}

// Post ...
// @Title 提交答卷
// @Description 学生提交考试答卷
// @Param	Authorization	header	string	true	"认证令牌"
// @Param	body		body 	models.TExamAnswer	true	"答卷内容"
// @Success 201 {int} models.TExamAnswer
// @Failure 403 请求体为空
// @router / [post]
func (c *TExamAnswerController) Post() {
	var v models.TExamAnswer
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		v.CreatedAt = time.Now()
		v.UpdatedAt = time.Now()
		var answers []models.StudentAnswer
		json.Unmarshal([]byte(v.Content), &answers)
		v.Score, v.Analysis, err = models.ExamDeepSeek(answers)
		if err != nil {
			c.Ctx.Output.SetStatus(400)
			c.Data["json"] = utils.Export(1001, "ExamDeepSeek 失败", err.Error())
			return
		}
		if _, err := models.AddTExamAnswer(&v); err == nil {
			c.Ctx.Output.SetStatus(201)
			c.Data["json"] = utils.Export(1000, "提交成功", &v)
		} else {
			c.Data["json"] = utils.Export(1001, "提交失败", err.Error())
		}
	} else {
		c.Data["json"] = utils.Export(1001, "解析失败", err.Error())
	}
	c.ServeJSON()
}

// GetOne ...
// @Title 获取单个答卷
// @Description 根据ID获取答卷详情
// @Param	Authorization	header	string	true	"认证令牌"
// @Param	id		path 	string	true	"答卷ID"
// @Success 200 {object} models.TExamAnswer
// @Failure 403 ID为空
// @router /:id [get]
func (c *TExamAnswerController) GetOne() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	v, err := models.GetTExamAnswerById(id)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "查询失败", err.Error())
	} else {
		c.Data["json"] = utils.Export(1000, "查询成功", &v)
	}
	c.ServeJSON()
}

// GetAll ...
// @Title 获取所有答卷
// @Description 获取答卷列表
// @Param	Authorization	header	string	true	"认证令牌"
// @Success 200 {object} models.TExamAnswer
// @Failure 403
// @router / [get]
func (c *TExamAnswerController) GetAll() {
	exams, err := models.GetAllTExamAnswer()
	if err != nil {
		c.Data["json"] = utils.Export(1001, "查询失败", err.Error())
	} else {
		c.Data["json"] = utils.Export(1000, "查询成功", exams)
	}
	c.ServeJSON()
}

// Put ...
// @Title 更新答卷
// @Description 根据ID更新答卷信息（如评分）
// @Param	Authorization	header	string	true	"认证令牌"
// @Param	id		path 	string	true	"要更新的答卷ID"
// @Param	body		body 	models.TExamAnswer	true	"答卷内容"
// @Success 200 {object} models.TExamAnswer
// @Failure 403 ID不是整数
// @router /:id [put]
func (c *TExamAnswerController) Put() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	v := models.TExamAnswer{Id: id}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		v.UpdatedAt = time.Now()
		if err := models.UpdateTExamAnswerById(&v); err == nil {
			c.Data["json"] = utils.Export(1000, "更新成功", &v)
		} else {
			c.Data["json"] = utils.Export(1001, "更新失败", err.Error())
		}
	} else {
		c.Data["json"] = utils.Export(1001, "解析失败", err.Error())
	}
	c.ServeJSON()
}

// Delete ...
// @Title 删除答卷
// @Description 根据ID删除答卷
// @Param	Authorization	header	string	true	"认证令牌"
// @Param	id		path 	string	true	"要删除的答卷ID"
// @Success 200 {string} 删除成功
// @Failure 403 ID为空
// @router /:id [delete]
func (c *TExamAnswerController) Delete() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	if err := models.DeleteTExamAnswer(id); err == nil {
		c.Data["json"] = utils.Export(1000, "删除成功", id)
	} else {
		c.Data["json"] = utils.Export(1001, "删除失败", err.Error())
	}
	c.ServeJSON()
}

// GetByExamId ...
// @Title 根据考试ID获取答卷列表
// @Description 根据考试ID获取所有相关答卷
// @Param	Authorization	header	string	true	"认证令牌"
// @Param	exam_id		path 	string	true	"考试ID"
// @Success 200 {object} models.TExamAnswer
// @Failure 403 exam_id为空
// @router /exam/:exam_id [get]
func (c *TExamAnswerController) GetByExamId() {
	examIdStr := c.Ctx.Input.Param(":exam_id")
	examId, _ := strconv.Atoi(examIdStr)
	exams, err := models.GetTExamAnswersByExamId(examId)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "查询失败", err.Error())
	} else {
		c.Data["json"] = utils.Export(1000, "查询成功", exams)
	}
	c.ServeJSON()
}

// GetByStudentSn ...
// @Title 根据学生学号获取答卷列表
// @Description 根据学生学号获取所有答卷
// @Param	Authorization	header	string	true	"认证令牌"
// @Param	student_sn		path 	string	true	"学生学号"
// @Success 200 {object} models.TExamAnswer
// @Failure 403 student_sn为空
// @router /student/:student_sn [get]
func (c *TExamAnswerController) GetByStudentSn() {
	studentSnStr := c.Ctx.Input.Param(":student_sn")
	studentSn, _ := strconv.Atoi(studentSnStr)
	exams, err := models.GetTExamAnswersByStudentSn(studentSn)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "查询失败", err.Error())
	} else {
		c.Data["json"] = utils.Export(1000, "查询成功", exams)
	}
	c.ServeJSON()
}

// GetByStudentSnAndExamId ...
// @Title 查询学生是否已完成试卷
// @Description 根据学生学号和考试ID查询学生是否已完成试卷，如果已完成则返回答卷内容
// @Param	Authorization	header	string	true	"认证令牌"
// @Param	student_sn		path 	string	true	"学生学号"
// @Param	exam_id			path 	string	true	"考试ID"
// @Success 200 {object} models.TExamAnswer
// @Failure 403 参数不合法
// @router /student/:student_sn/exam/:exam_id [get]
func (c *TExamAnswerController) GetByStudentSnAndExamId() {
	studentSn := c.Ctx.Input.Param(":student_sn")
	examIdStr := c.Ctx.Input.Param(":exam_id")

	examId, err := strconv.Atoi(examIdStr)
	if err != nil {
		c.Data["json"] = utils.Export(1001, "参数错误", "考试ID必须是数字")
		c.ServeJSON()
		return
	}

	examAnswer, err := models.GetTExamAnswerByStudentSnAndExamId(studentSn, examId)
	if err != nil {
		// 如果没有找到记录，则返回空对象表示未完成试卷
		c.Data["json"] = utils.Export(1000, "查询成功", nil)
	} else {
		// 如果找到了记录，则返回答卷内容
		c.Data["json"] = utils.Export(1000, "查询成功", examAnswer)
	}
	c.ServeJSON()
}
